//
//  WWOAuthViewController.swift
//  SinWEiBo
//
//  Created by 胡良志 on 2018/3/19.
//  Copyright © 2018年 HuLiangZhi. All rights reserved.
//  请求授权页面 

import UIKit
import SVProgressHUD
import YYModel
//swift4.0文件前面要加一个反斜杠
//let path = (NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last! as NSString).appending("/account.plist")
let path = (NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last! + "/account.plist")

class WWOAuthViewController: UIViewController {

    let webView = UIWebView()
    
    override func loadView() {
        self.view = webView
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .done, target: self, action: #selector(back))
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "快速登录", style: .done, target: self, action: #selector(speed))
        //请求oauth
        loadOauth();
        
    }
    //视图即将消失的时候dismiss掉指示器
    override func viewWillDisappear(_ animated: Bool) {
        SVProgressHUD.dismiss()
    }
    
    //请求授权
    func loadOauth(){

        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + app_key + "&redirect_uri=" + app_callBack
        let url = URL(string: urlString)
        let req = URLRequest(url: url!)
        webView.loadRequest(req)
    }
    
    //快速登录方法
    @objc func speed (){
        let jsString = "document.getElementById('userId').value = '15250005235', document.getElementById('passwd').value = 'huliangzhi456'"
        webView.stringByEvaluatingJavaScript(from: jsString)
    }
    //返回
    @objc func back (){
        dismiss(animated: true, completion: nil)
    }
    deinit {
        print("控制器移除 ")
    }
}



//MARK: UIWebViewDelegate
extension WWOAuthViewController:UIWebViewDelegate{
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //^ Optional(http://www.baidu.com/?code=310ddddec4ed67c461ded7c81d38d4c4)
        
        let urlString = request.url?.absoluteString ?? ""
        
        let flag = "code="
        if urlString.contains(flag) {
            let query = request.url?.query ?? ""
            let code = (query as NSString).substring(from: flag.characters.count)
            
            ////获取用户Token
            WWUserAccountViewModel.shared.loadAccessToken(code: code, finished: { (isSucess : Bool) in
                if !isSucess{
                    SVProgressHUD.showError(withStatus: "loadAccessToken网络错误")
                    return
                }
                print("请求成功")
                //切换跟控制器
               // UIApplication.shared.keyWindow?.rootViewController = WWWelComeViewController()
                //发出通知在APPdelegate中切换跟控制器
                NotificationCenter.default.post(name: NSNotification.Name(kchoseRootViewController), object: "Welcome")
                
                self.navigationController?.dismiss(animated: true, completion: nil)
            })
            return false
        }
        return true
    }
    
/*
    //获取用户Token
   private func loadAccessToken (code:String){
        let urlStirng = "https://api.weibo.com/oauth2/access_token"
        let parameters = ["client_id" : app_key,
                          "client_secret" : app_secret,
                          "grant_type" : "authorization_code",
                          "code" : code,
                          "redirect_uri" : app_callBack]
        WWNetworkTools.shared.request(method: .POST, urlString: urlStirng, parameters: parameters) { (responseObject, error) in
            if error != nil {
                //SVProgressHUD.showError(withStatus: "世界上最遥远的距离就是没有网络")
                return
            }
//            print(responseObject)
            self.loadUserInfo(dict: responseObject as! [String : Any])
        }
    }
    
    
    //请求用户信息
   private func loadUserInfo (dict : [String : Any]){
        let urlString = "https://api.weibo.com/2/users/show.json"
        let token = dict["access_token"]!
        let uid = dict["uid"]!
        let parameters = ["access_token" : token,
                          "uid" : uid]
        WWNetworkTools.shared.request(method: .GET, urlString: urlString, parameters: parameters) { (responseObject, error) in
            if error != nil {
                SVProgressHUD.showError(withStatus: "网络错误")
                return
            }
            //转换类型
            var userInfoDict = responseObject as! [String : Any]
            //合并字典
            for (key,value) in dict {
                userInfoDict[key] = value
            }
            //字典转模型
             let userAccount = WWUserAccount(dict: userInfoDict)
            
            //归档用户信息
            self.saveUserInfo(userAcconut: userAccount)
        }
     }
    
    
    //归档用户信息
    private func saveUserInfo (userAcconut:WWUserAccount){
        NSKeyedArchiver.archiveRootObject(userAcconut, toFile: path as String)
    }
    //读取磁盘
    private func loadUserInfo () -> WWUserAccount?{
        
        //调用解档的方法
        let account = NSKeyedUnarchiver.unarchiveObject(withFile: path as String)
        if let userAccount = account as? WWUserAccount {
            return userAccount
        }
        return nil
    }
    */
}







